<template>
  <div v-loading="loading" class="order-manage-main">
    <div class="top-container">
      <!-- tab start -->
      <div class="type-tab-container">
        <el-tabs v-model="filterForm.type" @tab-click="search(1)">
          <!-- <el-tab-pane label="快递物流订单" name="EXPRESS" />
          <el-tab-pane label="即时配送订单" name="LOCAL" />
          <el-tab-pane label="到店自提订单" name="SELF_PICKUP" />-->
          <el-tab-pane label="全部订单" name="all" />
          <el-tab-pane label="虚拟商品订单" name="VIRTUAL" />
          <el-tab-pane label="快递物流订单" name="EXPRESS" />
          <el-tab-pane label="同城配送订单" name="LOCAL" />
          <el-tab-pane label="到店自提订单" name="SELF_PICKUP" />
        </el-tabs>
      </div>
      <!-- tab end -->

      <!-- 筛选条件 start -->
      <div class="filter-container">
        <el-form
          ref="filterForm"
          :model="filterForm"
          :rules="rules"
          inline
          label-width="120px"
          size="small"
        >
          <el-form-item
            :class="
              filterForm.orderNo || filterForm.activityNo ? '' : 'is-required'
            "
            prop="createDate"
            label="下单时间："
          >
            <el-date-picker
              v-model="filterForm.createDate"
              :default-time="['00:00:00', '23:59:59']"
              type="datetimerange"
              range-separator="~"
              value-format="yyyy-MM-dd HH:mm:ss"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>
          <el-form-item prop="orderNo" label="订单编号：">
            <el-input v-model="filterForm.orderNo" maxlength="50" />
          </el-form-item>
          <el-form-item prop="subType" label="订单类型：">
            <el-select
              v-model="filterForm.subType"
              filterable
              placeholder="可通过名称搜索"
              style="width: 400px"
            >
              <el-option label="全部类型" value />
              <el-option
                v-for="(v, k) in subTypeSelectOptions"
                :key="k"
                :label="v"
                :value="k"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="storeId" label="下单店铺：">
            <el-select
              v-model="filterForm.storeId"
              filterable
              placeholder="可通过名称搜索"
              style="width: 400px"
            >
              <el-option label="全部门店" value />
              <el-option
                v-for="(item, index) in shopOptions"
                :key="index"
                :label="item.name"
                :value="item.storeId"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="memberPhone" label="下单人手机号：">
            <el-input v-model.trim="filterForm.memberPhone" maxlength="20" />
          </el-form-item>
          <el-form-item prop="phone" label="收货人手机号：">
            <el-input v-model.trim="filterForm.phone" maxlength="20" />
          </el-form-item>
          <el-form-item prop="businessRemark" label="商家备注：">
            <el-select
              v-model="filterForm.businessRemark"
              filterable
              clearable
              placeholder=""
              style="width: 400px"
            >
              <el-option :value="true" label="已备注" />
              <el-option :value="false" label="未备注" />
            </el-select>
          </el-form-item>

          <el-form-item prop="activityNo" label="活动批次：">
            <el-input
              v-model="filterForm.activityNo"
              clearable
              maxlength="50"
            />
          </el-form-item>

          <el-collapse-transition>
            <div v-show="isShowMoreFilter">
              <el-form-item prop="deliveryDate" label="发货时间：">
                <el-date-picker
                  v-model="filterForm.deliveryDate"
                  :default-time="['00:00:00', '23:59:59']"
                  type="datetimerange"
                  range-separator="~"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                />
              </el-form-item>
              <el-form-item label="支付方式：" prop="paymentMethods">
                <el-select
                  v-model="filterForm.paymentMethods"
                  filterable
                  multiple
                  collapse-tags
                  placeholder="可通过名称搜索"
                  class="w-400"
                  @change="(val) => idsChange(val, 'paymentMethods')"
                >
                  <el-option label="所有方式" value />
                  <el-option
                    v-for="item in paymentOptions"
                    :key="item.key"
                    :label="item.label"
                    :value="item.key"
                  />
                </el-select>
              </el-form-item>
              <!--<el-form-item-->
              <!--  prop="date"-->
              <!--  label="发货时间：">-->
              <!--  <el-date-picker-->
              <!--    v-model="filterForm.date"-->
              <!--    :default-time="['00:00:00', '23:59:59']"-->
              <!--    type="datetimerange"-->
              <!--    range-separator="~"-->
              <!--    value-format="yyyy-MM-dd HH:mm:ss"-->
              <!--    start-placeholder="开始日期"-->
              <!--    end-placeholder="结束日期"/>-->
              <!--</el-form-item>-->
              <!--<el-form-item-->
              <!--  prop="storeId"-->
              <!--  label="支付方式：">-->
              <!--  <el-select-->
              <!--    v-model="filterForm.storeId"-->
              <!--    filterable-->
              <!--    placeholder="可通过名称搜索">-->
              <!--    <el-option-->
              <!--      label="支付方式"-->
              <!--      value/>-->
              <!--  </el-select>-->
              <!--</el-form-item>-->
              <!--<el-form-item-->
              <!--  prop="subType"-->
              <!--  label="是否预售：">-->
              <!--  <el-select-->
              <!--    v-model="filterForm.subType"-->
              <!--    filterable-->
              <!--    placeholder="可通过名称搜索">-->
              <!--    <el-option-->
              <!--      label="全部模式"-->
              <!--      value/>-->
              <!--    <el-option-->
              <!--      label="预售"-->
              <!--      value="PRESELL"/>-->
              <!--    <el-option-->
              <!--      label="非预售"-->
              <!--      value="DEFAULT"/>-->
              <!--  </el-select>-->
              <!--</el-form-item>-->
              <!--<el-form-item-->
              <!--  prop="storeId"-->
              <!--  label="定金尾款：">-->
              <!--  <el-select-->
              <!--    v-model="filterForm.storeId"-->
              <!--    filterable-->
              <!--    placeholder="可通过名称搜索">-->
              <!--    <el-option-->
              <!--      :value="0"-->
              <!--      label="已支付定金"/>-->
              <!--    <el-option-->
              <!--      :value="1"-->
              <!--      label="支付方式"/>-->
              <!--  </el-select>-->
              <!--</el-form-item>-->
            </div>
          </el-collapse-transition>
          <div>
            <el-form-item label=" ">
              <el-button type="primary" round @click="search(1)"
                >查 询
              </el-button>
              <el-button round @click="reset">重 置 </el-button>
              <el-button round @click="downExcel">导出 </el-button>
              <!--<el-button-->
              <!--  type="text"-->
              <!--  round-->
              <!--  @click="isShowMoreFilter=!isShowMoreFilter">{{ isShowMoreFilter ? '隐藏' : '展开' }}高级选项-->
              <!--</el-button>-->
            </el-form-item>
          </div>
        </el-form>
      </div>
      <!-- 筛选条件 end -->
    </div>

    <!-- 表格 start -->
    <div class="table-container app-main-content-box">
      <!-- 商品状态tab start -->
      <div class="status-tab-container">
        <el-tabs v-model="filterForm.status" @tab-click="search(1)">
          <el-tab-pane label="全部状态" name="all" />
          <el-tab-pane
            v-for="(v, k) in statusOptions"
            :key="k"
            :label="v"
            :name="k"
          />
        </el-tabs>
        <div v-if="filterForm.status === 'PAYED'">
          <el-tabs v-model="filterForm.subStatus" @tab-click="search(2)">
            <el-tab-pane label="已支付(全部)" name="all" />
            <el-tab-pane label="待发货/配送/自提" name="WAIT_DELIVERY" />
            <el-tab-pane label="拼团中(拼团)" name="WAIT_GROUPING" />
            <el-tab-pane label="待付尾款(预售)" name="WAIT_REMAINING" />
          </el-tabs>
        </div>
        <div v-if="filterForm.status === 'UNDERWAY'">
          <el-tabs v-model="filterForm.subStatus" @tab-click="search(2)">
            <el-tab-pane label="服务中(全部)" name="all" />
            <el-tab-pane label="已发货/配送中" name="DELIVERING" />
          </el-tabs>
        </div>
      </div>
      <!-- 商品状态tab end -->

      <!-- 列表 start-->
      <el-table :data="list" :span-method="arraySpanMethod" style="width: 100%">
        <el-table-column prop="orderNo" label="商品" width="220">
          <template slot-scope="scope">
            <!-- 单 -->
            <div v-if="scope.$index % 2 == 0" class="flexRBS">
              <div>
                <span>
                  订单编号：
                  <span class="app-text-color-primary">{{
                    scope.row.orderNo
                  }}</span>
                  <span
                    v-if="scope.row.subType !== 'DEFAULT'"
                    class="app-text-color-primary"
                    >【{{ subTypeOptions[scope.row.subType]
                    }}{{
                      scope.row.activityNo ? '：' + scope.row.activityNo : ''
                    }}】</span
                  > </span
                >&nbsp;&nbsp;&nbsp;
                <span>下单时间：{{ scope.row.createTime }}</span
                >&nbsp;&nbsp;&nbsp;
                <span
                  v-if="
                    scope.row.subStatus === 'FINISH' ||
                    scope.row.subStatus === 'CANCEL'
                  "
                  >完成时间：{{ scope.row.updateTime }}</span
                >&nbsp;&nbsp;&nbsp;
                <span
                  v-if="
                    scope.row.orderException && scope.row.orderException.reason
                  "
                  class="app-text-color-danger"
                  >订单异常：{{ scope.row.orderException.reason }}</span
                >
                <div>
                  <span class="app-line-one app-text-color-danger"
                    >商家备注：{{ scope.row.remark || '无' }}</span
                  >
                  <span class="app-line-one app-text-color-danger"
                    >顾客备注：{{
                      (scope.row.bizData &&
                        JSON.parse(scope.row.bizData) &&
                        JSON.parse(scope.row.bizData).remark) ||
                      '无'
                    }}</span
                  >
                </div>
              </div>
              <div>
                <!--<el-button-->
                <!--  type="text"-->
                <!--  icon="el-icon-printer"-->
                <!--  @click="handlePrint(scope.row.orderNo)">订单打印-->
                <!--</el-button>-->
                <el-button
                  type="text"
                  icon="el-icon-setting"
                  @click="handleOrder(scope.row.orderNo)"
                  >订单管理
                </el-button>
                <el-button
                  type="text"
                  icon="el-icon-printer"
                  @click="putSealTicket(scope.row.orderNo)"
                  >打印小票
                </el-button>
              </div>
            </div>
            <!-- 双 -->
            <ul v-else>
              <li
                v-for="(item, index) in scope.row.items"
                :key="index"
                class="common-row-start-box"
              >
                <div class="cover-img">
                  <img
                    v-if="item.coverImg"
                    :src="fileBaseUrl + item.coverImg"
                    alt
                    srcset
                  />
                </div>
                <div class="goods-title app-line-two">
                  <span
                    v-if="item.goodsType === 101"
                    class="app-text-color-primary"
                    >【搭配】</span
                  >{{ item.title }}
                </div>
              </li>
            </ul>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="SKU" width="180">
          <template slot-scope="scope">
            <!-- 双 -->
            <ul v-if="scope.$index % 2 !== 0">
              <li
                v-for="(item, index) in scope.row.items"
                :key="index"
                class="common-row-start-box"
              >
                <span class="app-line-two">{{
                  item.skuInfo
                    ? JSON.parse(item.skuInfo).length > 0
                      ? JSON.parse(item.skuInfo).join('、')
                      : '无'
                    : '无'
                }}</span>
              </li>
            </ul>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="单价/数量" width="150px">
          <template slot-scope="scope">
            <!-- 双 -->
            <ul v-if="scope.$index % 2 !== 0">
              <li
                v-for="(item, index) in scope.row.items"
                :key="index"
                class="common-row-start-box"
              >
                <div>￥{{ item.price / 100 }} × {{ item.num }}</div>
              </li>
            </ul>
          </template>
        </el-table-column>
        <el-table-column prop="allDiscountFee" label="优惠">
          <template slot-scope="scope">
            <!-- 双 -->
            <ul>
              <li class="common-row-start-box">
                <div>￥{{ scope.row.allDiscountFee / 100 }}</div>
              </li>
            </ul>
          </template>
        </el-table-column>
        <el-table-column prop="tradeFee" label="应付" width="150px">
          <template slot-scope="scope">
            <!-- 双 -->
            <ul v-if="scope.$index % 2 !== 0">
              <li class="common-row-start-box">
                <div>
                  <div>￥{{ scope.row.tradeFee / 100 }}</div>
                  <div
                    v-if="
                      scope.row.subStatus === 'WAIT_REMAINING' &&
                      scope.row.orderPresell
                    "
                    class="app-text-color-danger"
                  >
                    缺尾款 ￥{{ scope.row.orderPresell.remainingFee / 100 }}
                  </div>
                </div>
              </li>
            </ul>
          </template>
        </el-table-column>
        <el-table-column prop="paymentMethod" label="支付方式" width="90px">
          <template slot-scope="scope">
            <!-- 双 -->
            <ul v-if="scope.$index % 2 !== 0">
              <li class="common-row-start-box">
                <div>{{ paymentKeyOptions[scope.row.paymentMethod] }}</div>
              </li>
            </ul>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="配送方式" width="150px">
          <template slot-scope="scope">
            <!-- 双 -->
            <ul v-if="scope.$index % 2 !== 0">
              <li class="common-row-start-box">
                <!--subType delivery leaderCollect leaderOrderNo-->
                <div
                  v-if="
                    scope.row.subType === 'GROUP' &&
                    scope.row.delivery.leaderCollect &&
                    scope.row.delivery.leaderOrderNo &&
                    scope.row.orderNo !== scope.row.delivery.leaderOrderNo
                  "
                >
                  <el-link
                    type="primary"
                    @click="handleOrder(scope.row.delivery.leaderOrderNo)"
                    >团长代收</el-link
                  >
                </div>
                <div v-else>
                  <div v-if="scope.row.orderType == 'EXPRESS'">快递配送</div>
                  <div v-else-if="scope.row.orderType == 'LOCAL'">同城配送</div>
                  <div v-else-if="scope.row.orderType == 'SELF_PICKUP'">
                    到店自提
                  </div>
                  <div v-else>自动发货</div>
                  <div
                    v-if="scope.row.delivery && scope.row.delivery.arrivalTime"
                    style="font-size: 12px"
                  >
                    <span v-if="scope.row.orderType == 'EXPRESS'"
                      >预期
                      {{
                        $momentMini(scope.row.delivery.arrivalTime).format(
                          'MM-DD'
                        )
                      }}
                      发货</span
                    >
                    <span v-if="scope.row.orderType == 'LOCAL'"
                      >{{
                        $momentMini(scope.row.delivery.arrivalTime).format(
                          'MM-DD HH:mm'
                        )
                      }}
                      送达</span
                    >
                    <span v-if="scope.row.orderType == 'SELF_PICKUP'"
                      >{{
                        $momentMini(scope.row.delivery.arrivalTime).format(
                          'MM-DD HH:mm'
                        )
                      }}
                      到店</span
                    >
                  </div>
                </div>
              </li>
            </ul>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="收货人" width="120">
          <template slot-scope="scope">
            <!-- 双 -->
            <ul v-if="scope.$index % 2 !== 0">
              <li class="common-column-start-box">
                <div v-if="scope.row.delivery">
                  <div class="app-line-one">
                    {{
                      scope.row.delivery.userName ||
                      scope.row.memberName ||
                      scope.row.customerName ||
                      '无'
                    }}
                  </div>
                  <div v-if="scope.row.delivery.phone">
                    {{ scope.row.delivery.phone }}
                  </div>
                </div>
                <div v-else>无</div>
              </li>
            </ul>
          </template>
        </el-table-column>
        <el-table-column prop="storeName" label="店铺">
          <template slot-scope="scope">
            <!-- 双 -->
            <ul v-if="scope.$index % 2 !== 0">
              <li class="common-row-start-box">
                <div>{{ scope.row.storeName }}</div>
              </li>
            </ul>
          </template>
        </el-table-column>
        <el-table-column prop="subStatus" label="状态" width="80px">
          <template slot-scope="scope">
            <!-- 双 -->
            <ul v-if="scope.$index % 2 !== 0">
              <li class="common-row-start-box">
                <!-- <div>{{statusOptions[scope.row.subStatus]}}</div> -->
                <el-tag v-if="scope.row.subStatus === 'WAITING'" type="danger"
                  >待支付
                </el-tag>
                <el-tag v-if="scope.row.subStatus === 'PAYED'"> 已支付 </el-tag>
                <el-tag v-if="scope.row.subStatus === 'UNDERWAY'">
                  服务中
                </el-tag>
                <el-tag
                  v-if="scope.row.subStatus === 'WAIT_REMAINING'"
                  type="danger"
                  >待付尾款
                </el-tag>
                <el-tag
                  v-if="scope.row.subStatus === 'WAIT_DELIVERY'"
                  type="danger"
                >
                  <span v-if="scope.row.orderType === 'EXPRESS'">待发货</span>
                  <span v-else-if="scope.row.orderType === 'LOCAL'"
                    >待配送</span
                  >
                  <span v-else-if="scope.row.orderType === 'SELF_PICKUP'"
                    >待提货</span
                  >
                  <span v-else-if="scope.row.orderType === 'VIRTUAL'"
                    >待发放</span
                  >
                  <span v-else>待发货</span>
                </el-tag>
                <el-tag
                  v-if="scope.row.subStatus === 'WAIT_GROUPING'"
                  type="danger"
                  >拼团中
                </el-tag>
                <el-tag
                  v-if="scope.row.subStatus === 'DELIVERING'"
                  type="danger"
                >
                  <span v-if="scope.row.orderType === 'EXPRESS'">已发货</span>
                  <span v-else-if="scope.row.orderType === 'LOCAL'"
                    >配送中</span
                  >
                  <span v-else-if="scope.row.orderType === 'VIRTUAL'"
                    >发放中</span
                  >
                  <span v-else>已发货</span>
                </el-tag>
                <el-tag v-if="scope.row.subStatus === 'FINISH'" type="success"
                  >已完成
                </el-tag>
                <el-tag v-if="scope.row.subStatus === 'CANCEL'" type="info"
                  >已取消
                </el-tag>
              </li>
            </ul>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination-direction
        v-if="paginationConfig.total !== 0"
        :config="paginationConfig"
        @sizeschange="sizesChange"
        @pagechange="pageChange"
      />
      <!-- 列表 end -->
    </div>
    <!-- 表格 end -->

    <!-- 组件 -->

    <HandleOrder ref="handleOrder" />
    <!-- <DialogSku /> -->
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { orderList, putSealTicket } from '@/views/wxaMallModule/api/order'
import { storeList } from '@/views/wxaMallModule/api/shop'
import HandleOrder from './components/HandleOrder'
import { downMallOrdersList } from '@/api/download'

export default {
  components: {
    HandleOrder
    // DialogSku,
  },
  data() {
    const validatorDate = (rule, value, callback) => {
      if (
        this.filterForm.orderNo ||
        this.filterForm.activityNo ||
        (value && value.length)
      ) {
        callback()
      } else {
        callback(new Error('请选择时间'))
      }
    }
    return {
      // 配置
      rules: {
        createDate: [
          {
            validator: validatorDate,
            trigger: ['blur', 'change']
          }
        ]
      },
      // 分页配置
      paginationConfig: {
        direction: 'center', // 分页位置
        layout: 'total, sizes, prev, pager, next, jumper', // 分页类型
        pageSizes: [10], // 分页pages
        total: 0,
        page: 1, // 页数-默认1
        pageSize: 10 // 每页条数-默认10
      },
      shopOptions: [],
      statusOptions: {
        WAITING: '待支付',
        PAYED: '已支付',
        UNDERWAY: '服务中',
        // WAIT_REMAINING: '待付尾款',
        // WAIT_DELIVERY: '待配送',
        FINISH: '已完成',
        CANCEL: '已取消'
      },
      subTypeSelectOptions: {
        DEFAULT: '常规销售',
        PRESELL: '预售',
        SEC_KILL: '秒杀',
        GROUP: '拼团'
      },
      subTypeOptions: {
        DEFAULT: '常规销售',
        DEPOSIT_PRESELL: '定金预售',
        FULL_PRESELL: '全款预售',
        PRESELL: '预售',
        SEC_KILL: '秒杀',
        GROUP: '拼团'
      },
      // 状态
      shopOptionsLoaded: false,
      isShowMoreFilter: true,
      loading: false,
      // 数据
      paymentMethods: [], // 所有的支付key
      lastPaymentMethodsArr: [], // 上一次选择
      filterForm: {
        level: 0,
        createDate: [
          this.$momentMini().subtract(6, 'days').format('YYYY-MM-DD') +
            ' 00:00:00',
          this.$momentMini().format('YYYY-MM-DD') + ' 23:59:59'
        ],
        orderNo: '',
        activityNo: '',
        memberPhone: '',
        phone: '',
        type: 'all',
        subType: '',
        storeId: '',
        status: 'all',
        subStatus: 'all',
        businessRemark: '',
        deliveryDate: [],
        paymentMethods: []
      },
      list: []
    }
  },
  computed: {
    ...mapGetters([
      'fileBaseUrl',
      'paymentOptions',
      'paymentKeyOptions',
      'userShopId'
    ]),
    msgGetOrderNo() {
      return this.$store.state.message.msgGetOrderNo
    }
  },
  watch: {
    msgGetOrderNo() {
      this.openMsgOrderInfo()
    },
    'filterForm.status'() {
      this.filterForm.subStatus = 'all'
    },
    'filterForm.activityNo'() {
      this.$refs.filterForm.validateField(['createDate'])
    },
    'filterForm.orderNo'() {
      this.$refs.filterForm.validateField(['createDate'])
    }
  },
  created() {},
  mounted() {
    if (this.$route.query.activityNo && this.$route.query.subType) {
      this.filterForm.createDate = []
      this.filterForm.activityNo = this.$route.query.activityNo
      this.filterForm.subType = this.$route.query.subType
    }
    if (this.$route.query.orderNo) {
      this.filterForm.createDate = []
      this.filterForm.orderNo = this.$route.query.orderNo
      this.handleOrder(this.$route.query.orderNo)
    }
    this.fetchData()
    // 订单消息跳转过来后弹窗
    this.openMsgOrderInfo()
    // this.$router.push({ query: {} }); 现在跳转后不清除传参信息了因为发票需求会用到
  },
  methods: {
    openMsgOrderInfo() {
      const { orderNo, path } = this.msgGetOrderNo
      const isCan = this.$route.path === path
      console.log(this.$route.path, path)
      if (orderNo && isCan) {
        this.handleOrder(orderNo)
        this.$store.dispatch('SetMsgOrderNo', {})
      }
    },
    // 打印小票
    putSealTicket(orderNo) {
      putSealTicket({ orderNo }).then((res) => {
        if (res.code === 0) {
          this.$notify({
            title: '成功',
            message: '打印成功',
            type: 'success'
          })
        }
      })
    },
    /**
     * 数据组
     */
    fetchData(
      pageNum = this.paginationConfig.page,
      pageSize = this.paginationConfig.pageSize
    ) {
      this.$refs.filterForm.validate(async (valid) => {
        if (valid) {
          if (!this.shopOptionsLoaded) await this.getShopOptions()
          this.filterForm.pageNum = pageNum
          this.filterForm.pageSize = pageSize
          const params = this.fetchFilterParams()
          this.loading = true
          orderList(params)
            .then((res) => {
              const list = []
              res.data.list.forEach((v) => {
                list.push(v, v)
              })
              this.list = list
              this.paginationConfig.total = res.data.total
              this.paginationConfig.page = res.data.pageNum
            })
            .finally(() => {
              this.loading = false
            })

          //
        }
      })
    },

    fetchFilterParams() {
      const params = Object.assign({}, this.filterForm)
      if (params.createDate && !params.orderNo) {
        params.beginTime = params.createDate[0]
        params.endTime = params.createDate[1]
      }
      // && (!params.orderNo || !params.activityNo)
      if (params.deliveryDate && params.deliveryDate.length) {
        params.deliveryBeginTime = params.deliveryDate[0]
        params.deliveryEndTime = params.deliveryDate[1]
      }
      params.paymentMethods = params.paymentMethods.includes('')
        ? []
        : params.paymentMethods
      if (
        params.level === 2 &&
        params.subStatus &&
        params.subStatus !== 'all'
      ) {
        params.status = params.subStatus
      }
      // 清除多余字段
      for (const key in params) {
        if (params[key] === '' || params[key] === 'all') {
          delete params[key]
        }
      }
      delete params.createDate
      delete params.deliveryDate
      // TODO 暂时解决门店id权限问题 不是总部强制查询当前门店id
      if (this.userShopId !== 0) {
        params.storeId = this.shopOptions[0].storeId
      }
      return params
    },

    // 获取所有门店Ids&终端ids&支付方式
    getIds() {
      const paymentMethods = ['']
      // 支付方式
      this.paymentOptions.forEach((v) => {
        paymentMethods.push(v.key)
      })
      this.paymentMethods = paymentMethods
      this.filterForm.paymentMethods = paymentMethods
    },

    // 分页sizes改变
    sizesChange() {
      this.fetchData()
    },

    // 分页page改变
    pageChange() {
      this.fetchData()
    },

    // 获取门店列表
    getShopOptions() {
      return new Promise((resolve, reject) => {
        storeList()
          .then((res) => {
            this.shopOptionsLoaded = true
            let shopList = []
            res.data.some((v) => {
              if (v.shopId === this.userShopId) {
                shopList = [v]
                return true
              } else {
                shopList.push(v)
              }
            })
            this.shopOptions = shopList
            resolve()
          })
          .catch((err) => {
            reject(err)
          })
      })
    },

    /**
     * 按钮组
     */
    // 查询
    search(level) {
      this.filterForm.level = level
      this.fetchData(1)
    },

    // 重置
    reset() {
      this.$refs.filterForm.resetFields()
      this.filterForm.paymentMethods = this.paymentMethods
    },

    // 导出
    downExcel() {
      const data = this.fetchFilterParams()
      downMallOrdersList(data).then((res) => {
        if (res.code === 0) {
          this.$alert('数据导出中，请稍后到数据下载中心进行下载', '提示', {
            confirmButtonText: '确定',
            center: true,
            type: 'success'
          })
        }
      })
    },

    //  订单打印
    handlePrint(orderNo) {
      // this.$refs.handleOrder.open({ orderNo }).then((res) => {
      // })
    },

    //  订单管理
    handleOrder(orderNo) {
      this.$refs.handleOrder.open({ orderNo }).then((res) => {
        this.fetchData()
      })
    },

    /**
     * 状态组
     */
    // 多选改变
    idsChange(val, type) {
      let lastIdsType = ''
      let idsType = ''
      switch (type) {
        case 'paymentMethods':
          lastIdsType = 'lastPaymentMethodsArr'
          idsType = 'paymentMethods'
          break
      }

      const lastVal = this[lastIdsType]
      if (val.includes('')) {
        this.filterForm[idsType] = this[idsType]
      }
      if (lastVal.includes('') && !val.includes('')) {
        this.filterForm[idsType] = []
      }
      if (lastVal.includes('') && val.includes('')) {
        val.splice(
          val.findIndex((v) => v === ''),
          1
        )
        this.filterForm[idsType] = val
      }
      if (!lastVal.includes('') && !val.includes('')) {
        if (val.length === this[idsType].length - 1) {
          this.filterForm[idsType] = [''].concat(val)
        }
      }
      this[lastIdsType] = this.filterForm[idsType]
    },

    /**
     * 方法组
     */
    // 合并单元格
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      if (rowIndex % 2 == 0) {
        return [1, 10]
      }
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.order-manage-main {
  ::v-deep {
    .el-tabs__header {
      margin-bottom: 0;
      background-color: #fff;
      border-radius: 0 0 5px 5px;
    }

    .el-tabs__item {
      font-weight: bold;
    }

    .el-tabs__active-bar {
      height: 4px;
    }
  }

  .el-input,
  .el-select {
    width: 400px;
  }
}

/* 头部 */
.top-container {
  padding: 24px 30px 0;
  border-radius: 5px;
  background-color: #fff;
}

/* 筛选 */
.filter-container {
  margin: 20px 0 10px;
}

/* 表格 */
.table-container {
  margin-top: 10px;

  ::v-deep {
    .el-table tr:nth-of-type(odd) td {
      border: none;
    }

    .el-table__row {
      td:not(:first-child) {
        vertical-align: top;
      }
    }

    .el-table td {
      border-bottom: 1px solid #dcdfe6;
      font-weight: bold;
    }
  }
}

/* 状态筛选 */
.status-tab-container {
  margin-bottom: 10px;
}

/* 表格内部通用盒子 */
.common-row-start-box {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  height: 50px;
  margin-bottom: 12px;

  .cover-img {
    margin-right: 10px;
    flex: 0 0 50px;
    height: 50px;
    border: 1px solid #e7e7e7;
  }

  .goods-title {
    font-weight: bold;
    color: #000;
  }
}

.common-column-start-box {
  display: flex;
  justify-content: center;
  flex-direction: column;
  height: 50px;
  margin-bottom: 12px;
}
</style>
